<template>
  <VBaseDialog
    @close="handleClose"
    @save="save"
    title="修改"
    :loading="loading"
    width="1100"
    destroy-on-close
  >
    <template #content>
      <el-form label-position="top" ref="formRef" :model="formValues">
        <div class="my-[16px] grid grid-cols-4 gap-x-3">
          <div>备库单号: {{ list?.tc_numbers_text || "-" }}</div>
          <div>配货单号/FBAID:{{ list?.fba_ids_str || "-" }}</div>
          <div>事业部: {{ list?.dept || "-" }}</div>
          <div>发货类型: {{ list?.shipment_type_text || "-" }}</div>
        </div>
        <div>
          <FormTitle title="基本信息" />
          <div class="grid grid-cols-4 gap-4">
            <div>发货仓: {{ list?.delivery_warehouse || "-" }}</div>
            <div>进口国: {{ list?.importing_country || "-" }}</div>
            <div>目的仓: {{ list?.dest_warehouse_name || "-" }}</div>
            <div>登记人: {{ list?.register_user || "-" }}</div>
            <div>物流商: {{ list?.logistics_name || "-" }}</div>
            <div>运输方式: {{ list?.transport_type_text || "-" }}</div>
            <div>是否包税: {{ list?.has_tax || "-" }}</div>
            <div>确认渠道: {{ list?.has_tax || "-" }}</div>
            <div>渠道计费类型: {{ list?.channel_billing_type_text || "-" }}</div>
          </div>
          <div class="grid grid-cols-4 gap-x-3 mt-4">
            <el-form-item label="备注">
              <el-input
                v-model="formValues.register_remark"
                placeholder="备注"
                class="w-full"
              />
            </el-form-item>
            <el-form-item label="物流提货日期">
              <el-date-picker
                v-model="formValues.delivery_take_time"
                type="date"
                placeholder="请选择"
                value-format="YYYY-MM-DD"
                class="w-full"
              />
            </el-form-item>
            <el-form-item label="物流单号">
              <el-input
                v-model="formValues.track_no"
                placeholder="物流单号"
                class="w-full"
              />
            </el-form-item>
            <el-form-item label="税号">
              <el-input v-model="formValues.tax_no" placeholder="税号" />
            </el-form-item>
          </div>
        </div>
        <div>
          <FormTitle title="重量信息" />
          <div class="grid grid-cols-4 gap-4">
            <div>订单票数: {{ list?.order_count || "-" }}</div>
            <div>箱数: {{ list?.box_count || "-" }}</div>
            <div>仓库实重: {{ list?.real_weight || "-" }}</div>
            <div>仓库最大重: {{ list?.max_weight || "-" }}</div>
          </div>
          <div class="grid grid-cols-4 gap-x-3 mt-4">
            <el-form-item label="仓库体积">
              <el-input-number
                v-model="formValues.volume"
                :precision="4"
                :controls="false"
                class="w-full"
                placeholder="仓库体积"
              />
            </el-form-item>
            <el-form-item label="仓库计费重(KG)">
              <el-input-number
                v-model="formValues.charge_weight"
                :controls="false"
                :precision="4"
                placeholder="仓库计费重"
                class="w-full"
              />
            </el-form-item>
            <el-form-item label="物流商计费重(KG)">
              <el-input-number
                v-model="formValues.logistics_charge_weight"
                :controls="false"
                :precision="4"
                class="w-full"
                placeholder="物流商计费重"
              />
            </el-form-item>
          </div>
        </div>
        <div>
          <FormTitle title="费用信息" />
          <div class="flex items-center my-3">
            <div>
              <span>总金额RMB: </span>
              <span class="text-[20px] font-bold">{{ totalAmount }}</span>
            </div>
            <div class="ml-[16px] mr-[4px]">单价</div>
            <el-input
              v-model="formValues.price"
              placeholder="请输入"
              class="w-[150px]"
            />
            <el-select
              v-model="formValues.price_currency"
              placeholder="请选择币种"
              filterable
              clearable
              class="w-[150px]"
              @change="handleRate1"
            >
              <el-option
                v-for="item in rateList"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
            <div class="ml-[16px]">
              <span>运费: </span>
              <span class="text-[20px] font-bold">{{ freight_amount }}</span>
            </div>
          </div>
          <vxe-grid v-bind="tableOptions" ref="tableRef">
            <template #freight="{ row }">
              <el-input-number
                v-model="row.freight"
                :controls="false"
                :precision="4"
                class="w-full"
              />
            </template>
            <template #freight_currency="{ row }">
              <el-select
                v-model="row.freight_currency"
                placeholder="请选择币种"
                class="w-full"
                filterable
                clearable
                @change="handleRate(row)"
              >
                <el-option
                  v-for="item in rateList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </template>
            <template #exchange_rate="{ row }">
              <el-input-number
                v-model="row.exchange_rate"
                :controls="false"
                :precision="4"
                disabled
                class="w-full"
              />
            </template>
            <template #freight_remark="{ row }">
              <el-input v-model="row.freight_remark" class="w-full" />
            </template>
          </vxe-grid>
        </div>
      </el-form>
    </template>
  </VBaseDialog>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { cost_list } from "./data.js";
import {
  invoiceRegisterDetail,
  invoiceRegisterUpdate,
  getExchangeRate,
} from "../../api.js";
import FormTitle from "@/components/Form/FormTitle.vue";
const props = defineProps({
  id: { type: [String, Number], default: "" },
});
const { option } = toRefs(props);
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const formValues = ref({
  id: null,
  register_remark: null,
  delivery_take_time: null,
  track_no: null,
  tax_no: null,
  volume: null,
  charge_weight: null,
  logistics_charge_weight: null,
  price: null,
  price_currency: null,
  price_exchange_rate: null,
});
const formRef = ref();
watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val);
        getExchangeRatelist(val);
      });
    }
  }
);
const list = ref([]);
const getDetail = async (id) => {
  const { data } = await invoiceRegisterDetail({ id });
  list.value = data || {};
  for (let key in formValues.value) {
    formValues.value[key] = data[key];
  }
  tableOptions.data = data.fees;
};
const rateList = ref([]);
const getExchangeRatelist = async (id) => {
  const { data } = await getExchangeRate({ id });
  const result = Object.entries(data).map(([label, value]) => ({
    label,
    value,
  }));
  rateList.value = result || [];
};
const freight_amount = computed(() => {
  const price = Number(formValues.value.price) || 0;
  const weight = Number(formValues.value.logistics_charge_weight) || 0;
  return price * weight;
});

const totalAmount = computed(() => {
  const rows = tableOptions.data || [];
  const taxFreightRow = rows.find(row => row.field === "tax_freight");
  const preTaxFreightRow = rows.find(row => row.field === "pre_tax_freight");
  const hasTaxFreight = taxFreightRow && Number(taxFreightRow.freight) > 0;
  const additionalTotal = rows.reduce((sum, row) => {
    if (row.field === "tax_freight" || row.field === "pre_tax_freight") {
      return sum;
    }
    const rate = Number(row.exchange_rate) || 1;
    const amount = Number(row.freight) || 0;
    return sum + amount * rate;
  }, 0);
  let taxAmount = 0;
  if (hasTaxFreight) {
    taxAmount = (Number(taxFreightRow.freight) || 0) * (Number(taxFreightRow.exchange_rate) || 1);
  } else if (preTaxFreightRow) {
    taxAmount = (Number(preTaxFreightRow.freight) || 0) * (Number(preTaxFreightRow.exchange_rate) || 1);
  }
  const freightRate = Number(formValues.value?.price_exchange_rate) || 1;
  const freightTotal = (freight_amount.value || 0) * freightRate;
  const total = additionalTotal + taxAmount + freightTotal;
  return total.toFixed(4);
});
const handleRate = (row) => {
  let obj = rateList.value.find((item) => item.label == row.freight_currency);
  row.exchange_rate = obj.value;
};
const handleRate1 = (val) => {
  let obj = rateList.value.find((item) => item.label == val);
  formValues.value.price_exchange_rate = obj.value;
};
const tableOptions = reactive({
  round: true,
  size: "small",
  columnConfig: {
    resizable: true,
  },
  data: [],
  columns: [
    {
      title: "费用名称",
      minWidth: 100,
      field: "name",
    },
    {
      title: "金额",
      minWidth: 100,
      field: "freight",
      slots: { default: "freight" },
    },
    {
      title: "币种",
      minWidth: 100,
      field: "freight_currency",
      slots: { default: "freight_currency" },
    },
    {
      title: "汇率",
      minWidth: 100,
      field: "exchange_rate",
      slots: { default: "exchange_rate" },
    },
    {
      title: "费用备注",
      minWidth: 100,
      field: "freight_remark",
      slots: { default: "freight_remark" },
    },
  ],
});
const tableRef = ref();
const save = async () => {
  const tableDataAll = tableRef.value.getTableData()?.fullData;
  const { code, message, data } = await invoiceRegisterUpdate({
    ...formValues.value,
    fees: tableDataAll,
  });
  if (code != 200) return ElMessage.error(message);
  ElMessage.success("修改成功!");
  handleClose(true);
};
const handleClose = async (refresh) => {
  formValues.value = {
    id: null,
    register_remark: null,
    delivery_take_time: null,
    track_no: null,
    tax_no: null,
    volume: null,
    charge_weight: null,
    logistics_charge_weight: null,
    price: null,
    price_currency: null,
  };
  formRef.value.resetFields();
  tableOptions.data = [];
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped></style>
